package com.chookss.home.publish;


import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;

import androidx.core.app.NotificationCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.mine.entity.MineInfoEntity;
import com.chookss.tools.FileUtilss;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UploadUserImageService extends Service {

    public static int NotificationId = 2;
    private int numAll = 0;
    private int docunmentAll = 0;
    private int currentNum = 0;
    private boolean beginUpload = false;//上传中不得重新开始
    private int picNum = 0;
    private int docunmentNum = 0;

    private List<MineInfoEntity> mineInfoEntityList = new ArrayList<>();
    private int upload_progress = 1;
    private boolean stopUpload = false;//默认正常上传  当true时切换账号中止上传

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        registerBoradcastReceiver();
        initNotification();
    }

    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
        MineInfoEntity mineInfoEntity = (MineInfoEntity) intent.getSerializableExtra("mineInfoEntity");
        if (mineInfoEntity != null) {
            mineInfoEntityList.add(mineInfoEntity);
            if (!beginUpload) {
                beginUpload = true;
                numAll=mineInfoEntityList.get(picNum).getRegisteredImageList().size()+mineInfoEntityList.get(picNum).getEducationImageList().size()+mineInfoEntityList.get(picNum).getCertificateImageList().size()+mineInfoEntityList.get(picNum).getContractImageList().size();
                docunmentAll=mineInfoEntityList.get(picNum).getDatabase().size();
                if (numAll > 0) {
                    getUrlData();
                } else if (docunmentAll > 0) {
                    uploadDocunment();
                } else {
                  uploadData();
                }
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private void getUrlData() {
        List<String> imgList=new ArrayList<>();
       if(upload_progress==1){
           if (mineInfoEntityList.get(picNum).getRegisteredImageList().size() == 0) {
               upload_progress = 2;
               getUrlData();
           } else {
               upload_progress = 1;
               imgList.addAll(mineInfoEntityList.get(picNum).getRegisteredImageList());
           }
       }else if(upload_progress==2){
            if (mineInfoEntityList.get(picNum).getEducationImageList().size() == 0) {
                upload_progress = 3;
                getUrlData();
            } else {
                upload_progress = 2;
                imgList.addAll(mineInfoEntityList.get(picNum).getEducationImageList());
            }
        }else if(upload_progress==3){
           if (mineInfoEntityList.get(picNum).getCertificateImageList().size() == 0) {
               upload_progress = 4;
               getUrlData();
           } else {
               upload_progress = 3;
               imgList.addAll(mineInfoEntityList.get(picNum).getCertificateImageList());
           }
       }else if(upload_progress==4){
           upload_progress = 4;
           if (mineInfoEntityList.get(picNum).getContractImageList().size() == 0) {
               if (docunmentAll > 0) {
                   uploadDocunment();
               } else {
                   uploadData();
               }
           } else {
               imgList.addAll(mineInfoEntityList.get(picNum).getContractImageList());
           }
       }

        int imgSize=imgList.size();
        for (int i = 0; i <imgList.size(); i++) {
            String picUrl = imgList.get(i);
            if(Utils.isNull(picUrl)){
                currentNum++;
                Message msg = handler.obtainMessage();
                msg.arg1 = (currentNum * 100) / numAll;
                handler.sendMessage(msg);
                if (currentNum>= numAll) {
                    //图片上传完毕
                    if (docunmentAll > 0) {
                        uploadDocunment();
                    } else {
                        uploadData();
                    }
                }else if(i==imgSize-1){
                    upload_progress++;
                    getUrlData();
                }
            }else if(picUrl.startsWith("http")){
                currentNum++;
                Message msg = handler.obtainMessage();
                msg.arg1 = (currentNum * 100) / numAll;
                handler.sendMessage(msg);
                if (currentNum>= numAll) {
                    //图片上传完毕
                    if (docunmentAll > 0) {
                        uploadDocunment();
                    } else {
                        uploadData();
                    }
                }else if(i==imgSize-1){
                    upload_progress++;
                    getUrlData();
                }
            }else {
                File file = new File(picUrl);
                int y = i;
                if (stopUpload) {
                    stopSelf();
                    return;
                }
                MyHttpRequest.uploadPicture(Urls.uploadPicture, this, "2", file, new JsonCallback<String>() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        JSONObject result = null;
                        JSONObject data = null;
                        try {
                            result = new JSONObject(response.body().toString());
                            if (result.getString("code").equals("200")) {
                                data = result.getJSONObject("data");
                                currentNum++;
                                Message msg = handler.obtainMessage();
                                msg.arg1 = (currentNum * 100) / numAll;
                                handler.sendMessage(msg);
                                if(upload_progress==1){
                                    mineInfoEntityList.get(picNum).getRegisteredImageList().set(y,data.getString("originalUrl"));
                                }else if(upload_progress==2){
                                    mineInfoEntityList.get(picNum).getEducationImageList().set(y,data.getString("originalUrl"));
                                }else if(upload_progress==3){
                                    mineInfoEntityList.get(picNum).getCertificateImageList().set(y,data.getString("originalUrl"));
                                }else if(upload_progress==4){
                                    mineInfoEntityList.get(picNum).getContractImageList().set(y,data.getString("originalUrl"));
                                }
                                FileUtilss.delFile(picUrl);
                                if (currentNum>= numAll) {
                                    //图片上传完毕
                                   if (docunmentAll > 0) {
                                        uploadDocunment();
                                    } else {
                                        uploadData();
                                    }
                                }else if(y==imgSize-1){
                                    upload_progress++;
                                    getUrlData();
                                }
                            } else if (result.getString("code").startsWith("400")) {
                                OkGoUtil.onErrorIntent(result.getString("code"), result.getString("msg"));
                            } else {
                                MyToast.show(result.getString("msg"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            KLog.i(e.getMessage()+"=="+e.toString());
                            MyToast.show("图片上传失败，请稍后重试");
                            stopSelf();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        MyToast.show("图片上传失败，请稍后重试");
                        stopSelf();
                    }
                });
            }
        }
    }
    private void uploadDocunment() {
        if (!Utils.isNull(mineInfoEntityList.get(picNum).getDatabase().get(docunmentNum).getDataCode())) {
            docunmentNum++;
            if (docunmentNum >=docunmentAll) {
                uploadData();
            } else {
                uploadDocunment();
            }
        } else {
            if (stopUpload) {
                stopSelf();
                return;
            }
            MyHttpRequest.uploadDataFileNew(Urls.uploadDataFile, this, new File(mineInfoEntityList.get(picNum).getDatabase().get(docunmentNum).getDataPath()), new JsonCallback<String>() {
                @Override
                public void onSuccess(Response<String> response) {
                    JSONObject result = null;
                    try {
                        result = new JSONObject(response.body().toString());
                        if (result.getString("code").equals("200")) {
                            Message msg = handler.obtainMessage();
                            msg.arg1 = (docunmentNum* 100) / docunmentAll;
                            handler.sendMessage(msg);
                            mineInfoEntityList.get(picNum).getDatabase().get(docunmentNum).setDataCode(result.getString("data"));
                            docunmentNum++;
                            if (docunmentNum >= docunmentAll) {
                                uploadData();
                            } else {
                                uploadDocunment();
                            }
                        } else {
                            if (result.getString("code").startsWith("400")) {
                                OkGoUtil.onErrorIntent(result.getString("code"), result.getString("msg"));
                            } else {
                                MyToast.show("资料上传失败，请稍后重试");
                            }
                            stopSelf();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        MyToast.show("资料上传失败，请稍后重试");
                        stopSelf();
                    }
                }

                @Override
                public void onError(Response<String> response) {
                    super.onError(response);
                    MyToast.show("资料上传失败，请稍后重试");
                    stopSelf();
                }
            });
        }
    }
    private void uploadData() {
        String registeredImage = "", educationImage = "", certificateImage = "",contractImage="",dataCode="";
        for (int i = 0; i < mineInfoEntityList.get(picNum).getRegisteredImageList().size(); i++) {
            if (i != 0) {
                registeredImage = registeredImage + "," + mineInfoEntityList.get(picNum).getRegisteredImageList().get(i);
            } else {
                registeredImage = mineInfoEntityList.get(picNum).getRegisteredImageList().get(i);
            }
        }
        for (int i = 0; i < mineInfoEntityList.get(picNum).getEducationImageList().size(); i++) {
            if (i != 0) {
                educationImage = educationImage + "," + mineInfoEntityList.get(picNum).getEducationImageList().get(i);
            } else {
                educationImage = mineInfoEntityList.get(picNum).getEducationImageList().get(i);
            }
        }
        for (int i = 0; i < mineInfoEntityList.get(picNum).getCertificateImageList().size(); i++) {
            if (i != 0) {
                certificateImage = certificateImage + "," + mineInfoEntityList.get(picNum).getCertificateImageList().get(i);
            } else {
                certificateImage = mineInfoEntityList.get(picNum).getCertificateImageList().get(i);
            }
        }
        for (int i = 0; i < mineInfoEntityList.get(picNum).getContractImageList().size(); i++) {
            if (i != 0) {
                contractImage = contractImage + "," + mineInfoEntityList.get(picNum).getContractImageList().get(i);
            } else {
                contractImage = mineInfoEntityList.get(picNum).getContractImageList().get(i);
            }
        }
        for (int i = 0; i < mineInfoEntityList.get(picNum).getDatabase().size(); i++) {
            if (i != 0) {
                dataCode = dataCode + "," + mineInfoEntityList.get(picNum).getDatabase().get(i).getDataCode();
            } else {
                dataCode = mineInfoEntityList.get(picNum).getDatabase().get(i).getDataCode();
            }
        }
        Map<String, String> map = new HashMap<>();
        map.put("id", mineInfoEntityList.get(picNum).getId());
        map.put("registeredNumber", mineInfoEntityList.get(picNum).getRegisteredNumber());
        map.put("bankName", mineInfoEntityList.get(picNum).getBankName());
        map.put("bankAddress", mineInfoEntityList.get(picNum).getBankAddress());
        map.put("bankNumber", mineInfoEntityList.get(picNum).getBankNumber());
        map.put("registeredImage", registeredImage);
        map.put("educationImage", educationImage);
        map.put("certificateImage", certificateImage);
        map.put("contractImage", contractImage);
        map.put("contractFile", dataCode);
        map.put("contractLength", mineInfoEntityList.get(picNum).getContractLength());
        if (stopUpload) {
            stopSelf();
            return;
        }
        MyHttpRequest.getDefault().postRequest(Urls.updateEmployeeInfo, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        picNum++;
                        if (picNum >= mineInfoEntityList.size()) {
                            EventBus.getDefault().post(new MyEvent("RefreshUserDetail"));
                            MyToast.show("保存成功");
                            Message msg = handler.obtainMessage();
                            msg.arg1 = 100;
                            handler.sendMessage(msg);
                            stopSelf();
                        } else {
                            numAll = 0;
                            upload_progress = 1;
                            numAll=mineInfoEntityList.get(picNum).getRegisteredImageList().size()+mineInfoEntityList.get(picNum).getEducationImageList().size()+mineInfoEntityList.get(picNum).getCertificateImageList().size()+mineInfoEntityList.get(picNum).getContractImageList().size();
                            docunmentNum=0;
                            docunmentAll=mineInfoEntityList.get(picNum).getDatabase().size();
                            if (numAll > 0) {
                                getUrlData();
                            } else if(docunmentAll>0) {
                                uploadDocunment();
                            }else{
                                uploadData();
                            }
                        }
                    } else {
                        Message msg = handler.obtainMessage();
                        msg.arg1 = 100;
                        handler.sendMessage(msg);
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"), jsonObject.getString("msg"));
                        } else {
                            MyToast.show(jsonObject.getString("msg"));
                        }
                        stopSelf();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    MyToast.show("保存失败，请稍后重试");
                    stopSelf();
                }
            }
        });
    }

    private NotificationManager mNManager;
    private Notification notification;

    private void initNotification() {
        //获得通知消息管理类对象
        mNManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Bitmap largeBitmap = GlideUtils.loadLogo(this);
        notification = new Notification(GlideUtils.loadLogoId(this), "带进条的提醒", System.currentTimeMillis());
//Android8.0以上必须添加 渠道 才能显示通知栏
        RemoteViews contentView = new RemoteViews(getApplication().getPackageName(), R.layout.vedio_upload);
        contentView.setProgressBar(R.id.progressbarUpload, 100, 0, false);
        contentView.setTextViewText(R.id.tvProcess, "已上传" + "0%");
        contentView.setImageViewResource(R.id.appdown_ivLogo, GlideUtils.loadLogoId(this));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //创建渠道
            String id = "news_upload_channel";
            String name = getResources().getString(R.string.app_name);
            NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_LOW);
            mNManager.createNotificationChannel(mChannel);
            //设置图片,通知标题,发送时间,提示方式等属性
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, id);
            int PROGRESS_MAX = 100;
            int PROGRESS_CURRENT = 0;
            builder.setCustomContentView(contentView).setWhen(System.currentTimeMillis())    //系统显示时间
                    .setSmallIcon(GlideUtils.loadLogoId(this))     //收到信息后状态栏显示的小图标
                    .setLargeIcon(largeBitmap)//大图标
                    .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)    //设置默认的三色灯与振动器
                    .setDefaults(Notification.DEFAULT_SOUND)    //设置系统的提示音
                    .setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false)
                    .setAutoCancel(true);       //设置点击后取消Notification
            notification = builder.build();
        } else {
            //设置图片,通知标题,发送时间,提示方式等属性
            Notification.Builder builder = new Notification.Builder(this);
            builder.setContent(contentView).setWhen(System.currentTimeMillis())    //系统显示时间
                    .setSmallIcon(GlideUtils.loadLogoId(this))     //收到信息后状态栏显示的小图标
                    .setLargeIcon(largeBitmap)//大图标
                    .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)    //设置默认的三色灯与振动器
                    .setDefaults(Notification.DEFAULT_SOUND)    //设置系统的提示音
                    .setAutoCancel(true);       //设置点击后取消Notification

            notification = builder.build();
        }
        mNManager.notify(NotificationId, notification);

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            notification.contentView.setProgressBar(R.id.progressbarUpload, 100, msg.arg1,
                    false);
            notification.contentView.setTextViewText(R.id.tvProcess, "已上传"
                    + msg.arg1 + "%");
            mNManager.notify(NotificationId, notification);
            if (msg.arg1 == 100) {
                mNManager.cancel(NotificationId);
            }
            super.handleMessage(msg);
        }
    };
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (context != null && intent != null && intent.getAction() != null) {

                if (action.equals(StaticClass.ACCOUNT_OUT)) {
                    stopSelf();
                }
            }
        }

    };
    private boolean registTag = false;//判断重复注册

    private void registerBoradcastReceiver() {
        if (mBroadcastReceiver != null) {
            IntentFilter myIntentFilter = new IntentFilter();
            myIntentFilter.addAction(StaticClass.ACCOUNT_OUT);// 关闭
            //注册广播
            LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, myIntentFilter);
            registTag = true;
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();

        } else {
            String msg = messageEvent.getMessage();
            if (!Utils.isNull(msg)) {
                if (msg.equals("Stop_File_Upload")) {
                    //中止上传任务
                    stopUpload = true;
                    MyApp.uploadRecordStatus = false;
                }
            }
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mNManager != null) {
            mNManager.cancel(NotificationId);
        }
    }
}